<template>
  <n-modal v-model:show="showModal" :mask-closable="false">
    <n-card
        title=" "
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
        style="width: 600px; position: fixed; left: 50%; top: 100px;margin-left: -300px"
    >
      <div class="py-4">
        <div style="position: absolute;top:30px;right:30px;">
          <nuxt-to href="javascript:void(0);"  @click.prevent="handleClose">
            <n-icon size="20px">
              <close></close>
            </n-icon>
          </nuxt-to>
        </div>
        <div class="flex flex-col" v-if="showInputFlag">
          <div class="flex justify-center mt-5 pb-14">
            <span class="mt-2">充值学习币数量：</span>
            <n-input-number button-placement="both" :precision="0"  v-model:value="coin" style="text-align: center;margin-right: 10px;" size="large" min="1" max="10000" placeholder="请输入数量"></n-input-number>
            <n-button rounded color="#343a40" @click="handleChangeCoin" size="large">确认充值</n-button>
          </div>
        </div>
        <div v-if="payShowFlag">
          <n-tabs :defaultValue="payMethod" justify-content="space-evenly" type="line" :on-update:value="handleChangeTab">
            <n-tab-pane name="weixin" tab="微信">
              <div class="flex justify-center flex-col items-center mt-5 pb-5">
                <n-image :src="payCodeUrl" width="240" height="240"/>
                <div class="mt--3">支付时间还剩：{{ payCount }}s</div>
              </div>
            </n-tab-pane>
            <n-tab-pane name="alipay" tab="支付宝">
              <div class="flex justify-center flex-col items-center mt-5 pb-5">
                <n-image :src="payCodeUrl" width="240" height="240"/>
                <div class="mt--3">支付的时间：{{ payCount }}s</div>
              </div>
            </n-tab-pane>
            <n-tab-pane name="code" tab="兑换码">
              <div class="flex justify-center  items-center mt-5" style="padding: 10px 40px 40px;">
                <n-input v-model:value="code" placeholder="请输入20位兑换码" maxlength="20" min="20" max="20"></n-input>
                <n-button class="ml-2" @click="handleDuiHuanCode" type="success">兑换</n-button>
              </div>
            </n-tab-pane>
          </n-tabs>
        </div>
      </div>
    </n-card>
  </n-modal>
</template>
<script setup>
  import QRCode from 'qrcode'
  const showModal = ref(false)
  const showInputFlag = ref(true)
  const payShowFlag = ref(false)
  // 获取支付数据
  const payData = ref({})
  const coin = ref(1)
  // 默认图的设置，防止出现裂图
  const payCodeUrl = ref("/imgs/1px.png")
  // 支付当前的课程
  const currentCourseId = ref("")
  // 支付的时长，单位是秒
  const payTotalTimer = 300
  const payCount = ref(payTotalTimer)
  const payMethod = ref("weixin")
  // 支付轮询定时器
  let payTimer = null
  // 支付时间计数的定时器
  let payCountTimer = null
  // 兑换码
  const code = ref("")

  // 打开支付窗口
  const handleOpen = () => {
    showModal.value = true
  }

  // 关闭
  const handleClose = ()=>{
    showModal.value = false
    payShowFlag.value = false
    // 生成和创建课程的微信支付二维码
    if (payTimer) clearInterval(payTimer);
    if (payCountTimer) clearInterval(payCountTimer);
    payCount.value = payTotalTimer
  }

  const handleChangeCoin = () => {
    payShowFlag.value = true
    showInputFlag.value = true
    if(payMethod.value == "weixin") {
      handleCreateNativeWeixin()
    }else{
      handleCreateNativeAlipay()
    }
  }

  // 生成课程的支付二维码
  const handleCreateNativeWeixin = async () => {
    try {
      if(coin.value<=1)coin.value=1
      if(coin.value>=10000)coin.value=10000
      var money = parseInt(coin.value)
      payMethod.value = "weixin"
      // 根据课程id获取下单的微信支付地址
      const resp = await useCreateNativeCoinApi(money,payMethod.value)
      // 获取服务端支付信息包括：微信支付地址，业务订单编号和状态success
      payData.value = resp.data
      // 生成二维码
      const qrCodeResp = await QRCode.toDataURL(resp.data.url, {
        width: 220,
        height: 240,
        margin: 2
      })
      // 把生成好的二维码的二进制的字符串赋值给状态数据管理payCodeUrl
      payCodeUrl.value = qrCodeResp
      // 保证每次都是从180开始
      payCount.value = payTotalTimer
      // 这两行代码是把原来开启的定时器关闭，保证每次支付都是最新的状态，（清楚旧的定时器，保证每次都是最新状态）
      if (payTimer) clearInterval(payTimer)
      if (payCountTimer) clearInterval(payCountTimer)
      // 开始查询, 这里立即执行一次，去查询用户是否支付和购买此课程
      handleListenerPaySuccess()
      payTimer = setInterval(handleListenerPaySuccess, 3000)
      // 时间计数倒计时
      payCountTimer = setInterval(handleListenerTime, 1000)
    } catch (e) {
      if (payTimer) clearInterval(payTimer)
      if (payCountTimer) clearInterval(payCountTimer)
      payCodeUrl.value = ""
      payCount.value = 0
      useMessage().error(e.message)
    }
  }

  // 生成课程的支付二维码
  const handleCreateNativeAlipay = async () => {
    try {
      if(coin.value<=1)coin.value=1
      if(coin.value>=10000)coin.value=10000
      var money = parseInt(coin.value)
      payMethod.value = "alipay"
      // 根据课程id获取下单的微信支付地址
      const resp = await useCreateNativeCoinApi(money,payMethod.value)
      // 获取服务端支付信息包括：微信支付地址，业务订单编号和状态success
      payData.value = resp.data
      // 生成二维码
      const qrCodeResp = await QRCode.toDataURL(resp.data.url, {
        width: 220,
        height: 240,
        margin: 2
      })
      // 把生成好的二维码的二进制的字符串赋值给状态数据管理payCodeUrl
      payCodeUrl.value = qrCodeResp
      // 保证每次都是从180开始
      payCount.value = payTotalTimer
      // 这两行代码是把原来开启的定时器关闭，保证每次支付都是最新的状态，（清楚旧的定时器，保证每次都是最新状态）
      if (payTimer) clearInterval(payTimer)
      if (payCountTimer) clearInterval(payCountTimer)
      // 开始查询, 这里立即执行一次，去查询用户是否支付和购买此课程
      handleListenerPaySuccess()
      payTimer = setInterval(handleListenerPaySuccess, 3000)
      // 时间计数倒计时
      payCountTimer = setInterval(handleListenerTime, 1000)
    } catch (e) {
      if (payTimer) clearInterval(payTimer)
      if (payCountTimer) clearInterval(payCountTimer)
      payCodeUrl.value = ""
      payCount.value = 0
      useMessage().error(e.message)
    }
  }

  // 支付查单
  const handleListenerPaySuccess = async () => {
    try {
      await useFindNativeByTradeNoCoinApi(payData.value.tradeNo,payMethod.value)
      useMessage().success("支付成功,可以去个人中心查看订单信息!")
      if (payTimer) clearInterval(payTimer);
      if (payCountTimer) clearInterval(payCountTimer);
      payCount.value = payTotalTimer
      // 关闭定时器
      setTimeout(() => {
        window.location.reload()
      }, 600)
    } catch (e) {
      if (e.code == 902) {
        useMessage().error(e.message)
        handleClose()
      }
    }
  }

  // 时间计数器
  const handleListenerTime = () => {
    payCount.value--
    if (payCount.value == 0) {
      // 关闭支付
      handleClose()
    }
  }

  // 选项卡改变
  const handleChangeTab = (value) => {
    if (value == "weixin"){
      showInputFlag.value = true
      payMethod.value = "weixin"
      handleCreateNativeWeixin(currentCourseId.value)
    }else if (value == "alipay"){
      payMethod.value = "alipay"
      showInputFlag.value = true
      handleCreateNativeAlipay(currentCourseId.value)
    }else if ( value == "code"){
      showInputFlag.value = false
      // 保证每次都是从180开始
      payCount.value = payTotalTimer
      // 这两行代码是把原来开启的定时器关闭，保证每次支付都是最新的状态，（清楚旧的定时器，保证每次都是最新状态）
      if (payTimer) clearInterval(payTimer)
      if (payCountTimer) clearInterval(payCountTimer)
      payMethod.value = ""
    }
  }


  // 兑换课程
  const handleDuiHuanCode = async () => {
    if (!code.value) {
      useMessage().error("请输入兑换码!")
      return
    }
    try {
      await useDuhuanUserWalletApi(code.value)
      useMessage().success("兑换成功")
      setTimeout(() => {
        window.location.reload()
      }, 600)
    }catch (e) {
      useMessage().error(e.message)
    }
  }


  defineExpose({
    handleOpen,
    handleClose
  })

</script>